'use client';

import {
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from '@/components/ui/form';
import { placeSearch } from '@/lib/poi';
import { useQuery } from '@tanstack/react-query';
import { useDebouncedValue } from 'foxact/use-debounced-value';
import { useState } from 'react';
import type { Control, Path } from 'react-hook-form';
import type { TypeOf, z } from 'zod';
import { Input } from '../ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';

export function PoiSearchFormItem<TSchema extends z.ZodType>({
  control,
  label,
  name,
}: {
  control: Control<z.infer<TSchema>>;
  label: string;
  name: Path<TypeOf<TSchema>>;
}) {
  const [value, setValue] = useState(
    control._defaultValues[name]?.address ?? '',
  );
  const search = useDebouncedValue(value, 1000);
  const [open, setOpen] = useState(false);
  const { data } = useQuery({
    queryKey: ['search', 'place', search],
    queryFn: () => placeSearch(search),
    staleTime: Number.POSITIVE_INFINITY,
  });

  return (
    <FormField
      control={control}
      name={name}
      render={({ field }) => (
        <FormItem>
          <FormLabel>{label}</FormLabel>
          <Popover open={open} onOpenChange={setOpen}>
            <FormControl>
              <PopoverTrigger asChild>
                <div>
                  <Input
                    placeholder={`输入${label}`}
                    value={value}
                    onKeyDown={() => setOpen(true)}
                    onChange={(e) => {
                      setValue(e.target.value);
                    }}
                  />
                </div>
              </PopoverTrigger>
            </FormControl>
            {data?.length && (
              <PopoverContent
                onOpenAutoFocus={(e) => e.preventDefault()}
                asChild
              >
                <div className="space-y-2 px-2">
                  {data?.map((poi) => (
                    <div
                      key={poi.id}
                      onClick={() => {
                        setValue(poi.address);
                        setOpen(false);
                        field.onChange(poi);
                      }}
                      className="cursor-pointer hover:bg-accent px-2 py-1 rounded"
                    >
                      {poi.address}
                    </div>
                  ))}
                </div>
              </PopoverContent>
            )}
          </Popover>
          <FormMessage />
        </FormItem>
      )}
    />
  );
}
